<template>
  <PageWrapper title="商品列表" contentFullHeight>
    <div v-if="!state.editStatus">
      <BasicTable
        @register="register"
        :dataSource="state.productList"
        :loading="state.listLoading"
        :pagination="state.pagination"
      >
        <template #toolbar>
          <a-button type="primary" @click="setEditStatus(true)">添加商品</a-button>
        </template>
        <template #add_time="{ record }">
          <span>{{ moment(record.add_time).format('YYYY-MM-DD HH:mm:ss') }}</span>
        </template>
        <template #operations="{ record }">
          <TableAction
            stopButtonPropagation
            :actions="[
              {
                label: '编辑',
                icon: 'ant-design:edit-outlined',
                onClick: handleEdit.bind(null, record),
                // auth: 'super', // 根据权限控制是否显示: 有权限，会显示
              },
              {
                label: '删除',
                icon: 'ic:outline-delete-outline',
                // auth: 'super', // 根据权限控制是否显示: 有权限，会显示
                popConfirm: {
                  title: '是否删除？',
                  confirm: handleDelete.bind(null, record),
                },
              },
            ]"
          />
        </template>
      </BasicTable>
    </div>
    <EditProduct
      v-else
      :type="state.editType"
      :id="state.editId"
      @set-edit-status="setEditStatus"
      @get-add-row="getAddRow"
      @get-update-row="getUpdateRow"
    />
  </PageWrapper>
</template>

<script lang="ts" setup>
  import { onMounted, reactive, unref } from 'vue';
  import { useShopGoodsStore } from '/@/store/modules/shopGoodsStore';
  import { PageWrapper } from '/@/components/Page';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import type { BasicColumn } from '/@/components/Table';
  import moment from 'moment';
  import EditProduct from './editProduct.vue';
  import { message } from 'ant-design-vue';

  interface stateModel {
    productList: object[] | any;
    listLoading: boolean;
    pagination: object[] | any;
    editStatus: boolean;
    editType: string;
    editId: number;
  }

  const shopGoodsStore = useShopGoodsStore();

  const state: stateModel = reactive({
    productList: [],
    listLoading: false,
    pagination: shopGoodsStore.$state.pagination,
    editStatus: false,
    editType: '',
    editId: 0,
  });

  const columns: BasicColumn[] = unref([
    {
      title: '商品名称',
      dataIndex: 'goods_name',
      width: 800,
    },
    {
      title: '商品价格（元）',
      dataIndex: 'goods_price',
      width: 150,
    },
    {
      title: '商品重量',
      dataIndex: 'goods_weight',
      width: 150,
    },
    {
      title: '商品数量',
      dataIndex: 'goods_number',
      width: 150,
    },
    {
      title: '商品创建时间',
      dataIndex: 'add_time',
      slots: { customRender: 'add_time' },
      width: 200,
    },
  ]);

  const [register, { getForm }] = useTable({
    title: '商品列表',
    titleHelpMessage: 'goods',
    rowKey: (record: any) => {
      return record.goods_id;
    },
    columns,
    striped: true,
    bordered: true,
    showTableSetting: false,
    useSearchForm: true,
    formConfig: {
      labelWidth: 100,
      schemas: [
        {
          field: `goods_name`,
          label: `商品名称`,
          component: 'Input',
          colProps: {
            xl: 12,
            xxl: 8,
          },
          componentProps: {
            onChange: (e: any) => {
              if (!e.target.value) {
                shopGoodsStore.$state.query = '';
              }
            },
          },
        },
      ],
      submitFunc: () => {
        if (getForm().getFieldsValue().goods_name) {
          shopGoodsStore.$state.query = getForm().getFieldsValue().goods_name;
        }
        return Promise.resolve();
      },
      resetFunc: () => {
        shopGoodsStore.$state.query = '';
        return Promise.resolve();
      },
    },
    actionColumn: {
      title: '操作',
      dataIndex: 'operations',
      slots: { customRender: 'operations' },
      width: 200,
    },
    onChange: (pagination) => {
      shopGoodsStore.$state.pagination.current = pagination.current;
      shopGoodsStore.$state.pagination.pageSize = pagination.pageSize;
    },
  });

  const getProductList = async () => {
    state.listLoading = true;
    try {
      const data = await shopGoodsStore.getProductList({});
      state.productList = data.goods;
      shopGoodsStore.$state.pagination.total = data.total;
    } catch (error) {
      console.error(error);
    }
    state.listLoading = false;
  };
  const setEditStatus = (bool: boolean) => {
    state.editStatus = bool;
    if (!bool) {
      state.editType = '';
      shopGoodsStore.$state.singleProduct = {};
    }
  };
  const getAddRow = (row: any) => {
    state.productList.unshift(row);
    setEditStatus(false);
  };
  const getUpdateRow = (row: any) => {
    state.productList.forEach((item: any) => {
      if (row.goods_id == item.goods_id) {
        item = row;
      }
    });
    setEditStatus(false);
  };
  const handleEdit = async (record: any) => {
    state.editType = 'edit';
    state.editId = record.goods_id;
    try {
      await shopGoodsStore.getSingleProduct({ id: record.goods_id });
      setEditStatus(true);
    } catch (error) {
      console.error(error);
    }
  };
  const handleDelete = async (record: any) => {
    console.log(record);
    try {
      await shopGoodsStore.deleteSingleProduct({ id: record.goods_id });
      message.success('删除成功');
      state.productList = state.productList.filter((item: any) => {
        return item.goods_id != record.goods_id;
      });
    } catch (error) {
      console.error(error);
    }
  };

  onMounted(() => {
    getProductList();
  });

  shopGoodsStore.$subscribe((mutation: any) => {
    if (
      mutation.events.key == 'current' ||
      mutation.events.key == 'pageSize' ||
      mutation.events.key == 'query'
    ) {
      getProductList();
    }
  });
</script>

<style scoped></style>
